<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends Base_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->model('smslog_m');
        $this->config->load('userset');
    }

    /**
     * 入口 路由分发
     */
    public function index()
    {
        $host = $_SERVER['HTTP_HOST'];
        if (strstr($host, 'wx')) {
            //微信端
            redirect(site_url('home/home'));
        } elseif (strstr($host, 'admin')) {
            //管理员端
            redirect(site_url('home/admin_login'));
        } elseif (strstr($host, 'vip')) {
            //合伙人端
            redirect(site_url('home/vip_login'));
        } else {
            $func         = $this->router->fetch_method(); // 当前方法名
            $data['func'] = $func;
            $this->load->set_front_theme('www');
            $data['viewmulu']  = base_url('public/www/');
            $data['foot_menu'] = 'www';

            $this->load->model('banner_m');
            $banner['pc']     = $this->banner_m->select(['type' => 0]);
            $banner['mobile'] = $this->banner_m->select(['type' => 1]);
            if ($banner['pc']) {
                foreach ($banner['pc'] as $key => $val) {
                    $banner['pc'][$key]['pic_url'] = str_replace('uploads/', "/uploads/", $val['pic_url']);
                    $banner['pc'][$key]['pic_url'] = str_replace('//uploads/', "/uploads/", $banner['pc'][$key]['pic_url']);
                }
            }
            $data['banner'] = $banner;
            // 报价列表
            // 报价列表
            $this->load->model('product_m');
            $this->load->model('category_m');
            $shwo_category = $this->category_m->get_cates_by("all_category = 1");

            $shwo_category = implode(",", array_column($shwo_category, "id"));

            $page_list = $this->product_m->select("category in ({$shwo_category})",4);

            if (!empty($page_list)) {
                $this->load->model('attachs_m');
                foreach ($page_list as $key => $value) {
                    $page_list[$key]['product_img'] = base_url($value["img"]);;
                }
            }
            // pp($page_list);
            // exit();
            // exit();
            $data['hot'] = $page_list;
            // 新闻
            $this->load->model('account_m');
            $news         = $this->account_m->select("", 2, 0, "id,title,keyword,describe,create_time,img");
            $data['news'] = $news;

            $this->load->model('category_m');
            $category         = $this->category_m->get_cates_by_pid(0);
            $data["category"] = $category;

            $this->load->model('zixunCategory_m');
            $zixuncategory         = $this->zixunCategory_m->get_all();
            $data["zixuncategory"] = $zixuncategory;

            // pp($data);exit();
            $this->load->view('index', $data);
        }
    }

    /**
     * 微信端首页
     */
    public function home()
    {

        $this->load->set_front_theme('wap');
        $data['viewmulu']  = base_url('public/wap/');
        $data['foot_menu'] = 'home';
        // 最新动态
        $this->load->model('file_m');
        $news         = $this->file_m->get_files();
        $data['news'] = $news;
        // 最新的通知
        if ($this->session->userdata('user_id')) {
            $uid         = $this->session->userdata('user_id');
            $data['msg'] = $this->message_m->get_new_message($uid);
        } else {
            $data['msg'] = "立即登陆，成为销售合伙人吧！";
        }
        // 报价列表
        $this->load->model('article_m');
        $page_list = $this->article_m->get_articles_list_by_cate_id(5);
        if (!empty($page_list)) {
            $this->load->model('attachs_m');
            foreach ($page_list as $key => $value) {
                if (!empty($value['article_cover'])) {
                    $access_key                     = $value['article_cover'];
                    $pic                            = $this->attachs_m->get_attachs_by($access_key);
                    $pic_path                       = base_url('uploads/article/' . $access_key . "/" . $pic[0]['file_name']);
                    $page_list[$key]['article_img'] = $pic_path;
                } else {
                    $page_list[$key]['article_img'] = base_url('public/wap/images/logo.png');;
                }
            }
        }
        $data['page_list'] = $page_list;
        // pp($data);exit();
        $this->load->view('home', $data);
    }

    /**
     * 微信端登录
     */
    public function login()
    {
        if ($this->auth->is_login()) {
            redirect(site_url('home/home'));
        }
        //如果维信绑定了 就自动登录
        $openid = $this->session->userdata('openid');
        if (isset($openid) && !empty($openid)) {
            // 查询改openid对应的用户
            $wx_user = $this->user_m->get_user_by_user_openid($openid);
            if (!empty($wx_user)) {
                $this->session->set_userdata('user_id', $wx_user['user_id']);
                redirect(site_url('home/home'));
            }
        }
        $this->load->set_front_theme('wap');
        $data['viewmulu']  = base_url('public/wap/');
        $data['foot_memu'] = 'home';
        $this->load->view('login', $data);
    }

    /**
     * 总管理后台登录
     */
    public function admin_login()
    {
        if ($this->auth->is_login()) {
            redirect(site_url(X_URL . 'home'));
        }
        if ($_POST && $this->validate_login_form()) {
            $usernames = $this->input->post('username', true);
            if (checkMobile($usernames)) {
                $username = $this->user_m->get_username_by_utel($usernames);
                $username = $username['user_name'];
            } elseif (validateEmail($usernames)) {
                $username = $this->user_m->get_username_by_uemail($usernames);
            } else {
                $username = $usernames;
            }
            if (!$this->user_m->check_ulock($username)) {
                show_message('您的帐号已经被锁定！', site_url('/'));
                exit;
            }
            $userpass = $this->input->post('password', true);
            $str      = [
                'user_name'     => $username,
                'user_password' => $userpass,
            ];
            if ($this->user_m->login($str)) {
                // 用户组是否已经禁用
                $uid      = $this->session->userdata('user_id');
                $userinfo = $this->user_m->get_user_by_user_id($uid);
                if (!$this->authGroup_m->is_user_group_able($userinfo['user_group'])) {
                    $this->user_m->del_user_key_by_user_id($uid);
                    $this->session->unset_userdata('user_id');
                    setcookie('loveme', '', time() - 3600, '/', '', false, true);
                    $this->session->sess_destroy();
                    show_message('用户组已被禁用！', site_url('/'));
                    exit;
                }
                //更新登陆次数
                $this->user_m->update_ulognum($uid);
                //更新最后登录时间
                $this->user_m->update_user($uid, ['user_logtime' => time()]);
                show_message('恭喜您，成功登陆本站！', site_url(X_URL . 'home'), 1);
                exit;
            } else {
                show_message('抱歉哦，登陆本站失败！', site_url('/'));
                exit;
            }
        }
        $data['web_title'] = '登陆 -- ' . $this->config->item('site_name');
        $data['top_memu']  = 'login';
        $this->load->set_front_theme('default');
        $data['viewmulu'] = base_url('public/default/');
        $this->load->view('user/login', $data);
    }

    private function validate_login_form()
    {
        $this->form_validation->set_rules('username', '帐号', 'trim|required|min_length[3]|xss_clean');
        $this->form_validation->set_rules('password', '密码', 'trim|required|min_length[6]|max_length[18]');
        $this->form_validation->set_message('required', "%s 不能为空！");
        $this->form_validation->set_message('min_length', "%s 最小长度不少于 %s 个字符！");
        $this->form_validation->set_message('max_length', "%s 最大长度不多于 %s 个字符！");
        if ($this->form_validation->run() == false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 发送验证码逻辑
     */
    public function ajax_send_sms()
    {
        $mobile = $this->input->get("mobile");

        if (empty($mobile)) {
            echo json_encode(['code' => 400, 'msg' => '参数缺失']);
            exit();
        }
        if (!$this->verifyMobile($mobile)) {
            echo json_encode(['code' => 200, 'msg' => '号码格式错误']);
            exit;
        }
        // 生成验证码
        $code = $this->creatCodeByRand();
        // 入库
        $data = [
            'mobile'     => $mobile,
            'yzm'        => $code,
            'type'       => 1,
            'createtime' => date("Y-m-d H:i:s", time()),
        ];
        if ($this->smslog_m->add_sms_log($data)) {
            //发送验证码
            $response = $this->send_sms_code($mobile, $code);
            // 返回
            if (isset($response->Code) && $response->Code == 'OK') {
                // 缓存
                $phoneCode          = $this->phoneCodeArr($mobile);
                $phoneCode[$mobile] = ['code' => $code, 'status' => 0];
                $this->session->set_userdata($mobile . '_info', $phoneCode);
                echo json_encode(['code' => 200, 'msg' => '发送成功']);
                exit();
            } else {
                echo json_encode(['code' => 400, 'msg' => '发送失败']);
                exit();
            }
        } else {
            echo json_encode(['code' => 400, 'msg' => '网络异常, 请稍后再试']);
            exit();
        }
    }

    /**
     * 短信验证码登录
     */
    public function sms_login_in()
    {
        $url    = $this->session->userdata('gourl');
        $mobile = $this->input->post("mobile");
        $yzm    = $this->input->post("yzm");
        // 根据mobile查询数据库
        $sms = $this->smslog_m->get_sms_log_by($mobile, $yzm, 0);
        if (!empty($sms)) {
            // 验证是否正确
            if (!$this->verifyPhoneCode($mobile, $yzm)) {
                echo json_encode(['code' => 400, 'msg' => "验证码不正确！"]);
                exit;
            }
            // 号码更新为已验证
            $this->smslog_m->sava_sms_log($sms['id'], ['is_checked' => 1]);
            // 查看用户是否已注册
            $user = $this->user_m->check_register_username_tel($mobile);
            //维信绑定
            $openid = $this->session->userdata('openid');
            if (isset($openid) && !empty($openid)) {
                $callback['wx_openid'] = $openid;
            }
            if (empty($user)) {
                // 新用户数据入库
                $salt  = get_salt();
                $admin = [
                    'user_name'     => $mobile,
                    'user_password' => password_dohash("123456", $salt),
                    'user_salt'     => $salt,
                    'user_credit'   => $this->config->item('credit_start'),
                    'user_regip'    => get_onlineip(),
                    'user_money'    => 0,
                    'user_group'    => 3, // 普通用户
                    'user_regtime'  => time(),
                    'user_logtime'  => time(),
                    'user_lock'     => 0,
                    'user_tel'      => $mobile,
                ];
                $this->user_m->register($admin);
                $new_id               = $this->db->insert_id();
                $callback['user_key'] = password_dohash($new_id, $salt);

                $this->user_m->update_user($new_id, $callback);
                $this->groupAcess_m->insert_user_access(['uid' => $new_id, 'group_id' => 3]);

                $user = $this->user_m->get_user_by_user_id($new_id);
            }
            // 记录登录缓存
            $this->session->set_userdata('user_id', $user['user_id']);
            if (empty($user['wx_openid'])) {
                if (isset($openid) && !empty($openid)) {
                    $this->user_m->update_user($user['user_id'], $callback);
                }
            }
            $loveme = password_dohash($user['user_id'], $user['user_salt']);
            if ($loveme) {
                $_COOKIE['loveme'] = $loveme;
                setcookie('loveme', $loveme, time() + 86500, '/', '', false, true);
                $this->user_m->update_user($user['user_id'], ['user_key' => $loveme]);
            }
            // 更新登录时间和威望值
            $uid = $this->session->userdata('user_id');
            //更新登陆次数
            $this->user_m->update_ulognum($uid);
            //更新最后登录时间
            $this->user_m->update_user($uid, ['user_logtime' => time()]);
            echo json_encode(['code' => 200, 'msg' => '登陆成功', 'url' => $url]);
            exit();
            exit;
        } else {
            if ($mobile == "13162107069") { // 测试账号
                $user = $this->user_m->check_register_username_tel($mobile);
                $this->session->set_userdata('user_id', $user['user_id']);
                echo json_encode(['code' => 200, 'msg' => '登陆成功', 'url' => $url]);
                exit();
                exit;
            } else {
                echo json_encode(['code' => 400, 'msg' => '网络异常, 请稍后再试']);
                exit();
            }
        }
    }

    /**
     * 生成验证码
     * @return string
     */
    private function creatCodeByRand()
    {
        $token = '';
        $len   = 6;
        for ($i = 0; $i < $len; $i++)
            $token .= chr(mt_rand(48, 57));
        return $token;
    }

    /**
     * 短信验证码接口
     * @param        $mobile 手机号码
     * @param        $code   验证码
     * @param string $temp   短信模板
     * @param string $type   模板自定义变量
     * @return stdClass
     */
    public function send_sms_code($mobile, $code, $temp = 'SMS_132295021', $type = 'code')
    {

        $this->load->library('alisms');
        $response = $this->alisms->sendSms("销售合伙人平台", $temp, $mobile, [$type => $code]);

        return $response;
//         return (object)['Code'=>"OK"];
    }

    /**
     * 验证手机号规则
     * @param $mobile
     * @return bool
     */
    public function verifyMobile($mobile)
    {
        $return = false;
        // 正则手机或固定电话
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        $isMob = "/^1[3-5,7,8]{1}[0-9]{9}$/";
        if (preg_match($isMob, $mobile) || preg_match($isTel, $mobile)) {
            $return = true;
        }
        return $return;
    }

    /**
     * 查询缓存
     * @param $mobile
     * @return array|mixed
     */
    private function phoneCodeArr($mobile)
    {
        $info = $this->session->userdata($mobile . "_info");
        if (!empty($info)) {
            return $info;
        }
        return [];
    }

    /**
     * 验证 手机验证码
     * @param  Int $mobile    手机号码
     * @param  Int $phoneCode 验证码
     * @return Boolean
     */
    private function verifyPhoneCode($mobile, $phoneCode)
    {
        $result       = false;
        $phoneCodeArr = $this->phoneCodeArr($mobile);
        if (isset($phoneCodeArr[$mobile])) {
            if ($phoneCodeArr[$mobile]['code'] == $phoneCode) {
                $phoneCodeArr[$mobile]['status'] = 1;
                $this->session->set_userdata($mobile . '_info', $phoneCodeArr);
                $result = true;
            }
        }
        return $result;
    }

    /**
     * 微信首页单页详情
     * @param $cate_id
     * @return bool
     */
    public function page($cate_id)
    {

        if (!$cate_id) {
            return false;
        }
        $this->load->set_front_theme('wap');
        $this->load->model('article_m');
        $page         = $this->article_m->get_articles_by_cate_id($cate_id);
        $data['page'] = $page;
        $this->load->view('page', $data);
    }

    /**
     * 新闻
     * @param $id
     * @return bool
     */
    public function news($id)
    {
        if (!$id) {
            return false;
        }
        $this->load->set_front_theme('wap');
        $this->load->model('article_m');
        $news         = $this->article_m->get_news_by_id($id);
        $data['news'] = $news;
        $this->load->view('news', $data);
    }

    /**
     * 新闻列表
     * @param $cate_id
     * @return bool
     */
    public function page_list($cate_id)
    {
        if (!$cate_id) {
            return false;
        }
        $this->load->set_front_theme('wap');
        $this->load->model('article_m');
        $page_list = $this->article_m->get_articles_list_by_cate_id($cate_id);
        if (!empty($page_list)) {
            $this->load->model('attachs_m');
            foreach ($page_list as $key => $value) {
                if (!empty($value['article_cover'])) {
                    $access_key                     = $value['article_cover'];
                    $pic                            = $this->attachs_m->get_attachs_by($access_key);
                    $pic_path                       = base_url('uploads/article/' . $access_key . "/" . $pic[0]['file_name']);
                    $page_list[$key]['article_img'] = $pic_path;
                } else {
                    $page_list[$key]['article_img'] = base_url('public/wap/images/logo.png');;
                }
            }
        }
        $data['page_list'] = $page_list;
        $this->load->view('page_list', $data);
    }

    public function vip_login()
    {
        if ($this->auth->is_login()) {
            redirect(site_url(V_URL . 'home'));
        }
        $this->load->set_front_theme('vip');
        $data['viewmulu']  = base_url('public/vip/');
        $data['foot_memu'] = 'home';
        $this->load->view('login', $data);
    }

    public function excel_export()
    {

//        $data = array(
//            array(
//                '111',
//                '111',
//                '111',
//            ),
//        );
//        $fileName = "test_excel";
//        $dates = date("Ymd_His",time());
//        $Path='uploads/excel/';
//        $savePath=FCPATH.$Path;
//        if(!file_exists($savePath)){
//            mkdir($savePath,0777,true);
//        }
//        $headArr = array("品牌","号码","底价");
//        $ex='2007';
//        if($ex=='2003'){
//            $files = $fileName."_".$dates.".xls";
//        }elseif($ex=='2007'){
//            $files = $fileName."_".$dates.".xlsx";
//        }
//        getExcel($fileName,$headArr,$data,$ex,$dates,$savePath);
        $Path     = 'uploads/excel/';
        $savePath = FCPATH . $Path;
        $res      = importExecl($savePath . "test_excel_20180528_041057.xlsx");
        pp($res);
        exit();
    }

    /**
     * 生成模板
     */
    public function create_excel_template()
    {

        $this->load->model('category_m');
        $category = $this->category_m->get_all_cates();

        if (!empty($category)) {
            $cateStr = "";
            foreach ($category as $key => $value) {
                $cateStr .= $value['category_name'] . ',';
            }
        }
        $cateStr = substr($cateStr, 0, strlen($cateStr) - 1);
//        pp($cateStr);exit();

        require_once(APPPATH . 'third_party/PHPExcel.php');
        require_once(APPPATH . 'third_party/PHPExcel/Writer/Excel2007.php');
        require_once(APPPATH . 'third_party/PHPExcel/IOFactory.php');

        $headArr = ["分类(下拉)", "货品名称(必填)", "货品规格(必填)", "单价(必填)", "生产工艺(必填)", "料号(选填)"];
        //创建新的PHPExcel对象
        $objPHPExcel = new PHPExcel();
        $objProps    = $objPHPExcel->getProperties();

        //设置表头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $key += 1;
        }
        $key2    = ord("A");
        $example = ["胶带", "PO胶袋", "230*320", "3.6", "小边开口", ""];
        foreach ($example as $v) {
            $colum2 = chr($key2);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum2 . '2', $v);
            $key2 += 1;
        }

        $objActSheet = $objPHPExcel->getActiveSheet();

        for ($k = 3; $k < 500; $k++) {
            $objValidation = $objActSheet->getCell("A" . $k)->getDataValidation(); //这一句为要设置数据有效性的单元格

            $objValidation->setType(PHPExcel_Cell_DataValidation::TYPE_LIST)
                ->setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_INFORMATION)
                ->setAllowBlank(false)
                ->setShowInputMessage(true)
                ->setShowErrorMessage(true)
                ->setShowDropDown(true)
                ->setErrorTitle('输入的值有误')
                ->setError('您输入的值不在下拉框列表内.')
                ->setPromptTitle('产品分类')
                ->setFormula1('"' . $cateStr . '"');
        }

        $objActSheet->getColumnDimension('a')->setWidth(20);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('b')->setWidth(20);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('c')->setWidth(20);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('d')->setWidth(20);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('e')->setWidth(25);//改变此处设置的长度数值
        $objActSheet->getColumnDimension('f')->setWidth(20);//改变此处设置的长度数值

        $fileName = "excel_template.xlsx";
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        $objPHPExcel->getActiveSheet()->setTitle('Simple');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        //将输出重定向到一个客户端web浏览器(Excel2007)
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $Path     = 'upload/excel_template/';
        $savePath = FCPATH . $Path;
        if (!file_exists($savePath)) {
            mkdir($savePath, 0777, true);
        }
        $savename = $savePath . $fileName;

        $objWriter->save($savename); //脚本方式运行，保存在当前目录

        echo $savename;
        exit();
    }

}
